package main

import (
	"fmt"
	"net/http"
)
func get_cookie(w http.ResponseWriter, r *http.Request)  {
	//w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	//w.Header().Set("Access-Control-Allow-Credentials", "true")    //设置为true，允许ajax异步请求带cookie信息
	//w.Header().Set("Access-Control-Allow-Origin",r.Header.Get("Origin"))
	//
	////w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") //允许请求方法
	//
	//w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	//w.Header().Add("Access-Control-Allow-Headers", "Access-Token")
	//fmt.Println("Access-Control-Allow-Origin=",r.Header.Get("Origin"))

	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Set("Access-Control-Allow-Credentials", "true")    //设置为true，允许ajax异步请求带cookie信息
	w.Header().Set("Access-Control-Allow-Origin",r.Header.Get("Origin"))
	w.Header().Set("Access-Control-Allow-Headers","content-type")
	body:=""
	name,err:=r.Cookie("access_token")
	if err != nil {
		fmt.Println("获取cookie错误！,err:", err)
		//return
	}
	if name==nil {
		fmt.Println("没有获取到cookie。");
		//,HttpOnly: false,Secure: false
		c1:=http.Cookie{Name: "access_token",Value: "123",HttpOnly: false,Secure: false}
		http.SetCookie(w,&c1);
		r.AddCookie(&c1);
		fmt.Println("创建成功！cookie name");
		body="没有获取到cookie。";
	}else {
		fmt.Println("获取到了cookie：access_token=",name.Value);
		body="获取到了cookie：access_token="+name.Value;
	}
	w.Write([]byte(body));
}
func main() {
	http.HandleFunc("/hello", get_cookie)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("http server failed, err:%v\n", err)
		return
	}
}

